import _thread
import socket
import sys
from time import sleep

host = '127.0.0.1'
port = 9999
should_exit = False


def print_server(conn):
    global should_exit
    while True:
        try:
            data = str(conn.recv(1024), "utf8")
            if len(data) > 0:
                print(data)
        except:
            should_exit = True
            exit(0)


def heart_beat(conn):
    global should_exit
    while True:
        try:
            conn.send(bytes("heartbeat", encoding="utf8"))
        except:
            should_exit = True
            exit(0)
        sleep(2)


def deal_with_input(conn):
    global should_exit
    while True:
        command = input()
        try:
            conn.send(bytes(command, encoding="utf8"))
        except:
            should_exit = True
            exit(0)


if __name__ == '__main__':
    obj = socket.socket()
    obj.connect((host, port))
    _thread.start_new_thread(print_server, (obj,))
    _thread.start_new_thread(heart_beat, (obj,))
    _thread.start_new_thread(deal_with_input, (obj,))
    while True:
        if should_exit:
            break
    sys.exit()
